/**
 * 这个文件中模拟的就是服务端的代码逻辑
 */

const express = require('express');
const { createServer } = require('node:http');
const { join } = require('node:path');

const { Server } = require('socket.io');

const app = express();
const server = createServer(app);

// 创建服务端 Socket 对象
const io = new Server(server);
// 等待客户端的连接
io.on('connection', (socket) => {
  console.log('a user connected');

  // 在客户端连接到服务端的时候，向客户端发送一个欢迎消息
  socket.emit('onClientReceive', '欢迎加入聊天室');

  // 注册事件监听，用于接收客户端发送到服务端的消息
  socket.on('onServerReceive', (msg) => {
    console.log('服务端接收到消息message: ' + msg);
    // 将接收到的消息再发送给所有连接到服务端的客户
    io.emit('onClientReceive', msg);
  });

  // 当连接的客户端断开连接时执行
  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
});

app.get('/', (req, res) => {
  res.sendFile(join(__dirname, 'index.html'));
});

server.listen(3000, () => {
  console.log('server running at http://localhost:3000');
});